package cn.lijiajia3515.cairo.example1.config;


import cn.lijiajia3515.cairo.security.web.authentication.CairoHttpMessageAccessDeniedHandler;
import cn.lijiajia3515.cairo.security.web.authentication.CairoHttpMessageAuthenticationEntryPoint;
import cn.lijiajia3515.cairo.security.web.authentication.CairoHttpMessageAuthenticationFailedHandler;
import cn.lijiajia3515.cairo.security.web.authentication.CairoHttpMessageAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration(proxyBeanMethods = false)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {

	@Bean
	@Order(1000)
	SecurityFilterChain mySecurity(HttpSecurity http,
								   CairoHttpMessageAuthenticationEntryPoint cairoAuthenticationEntryPoint,
								   CairoHttpMessageAuthenticationFailedHandler cairoAuthenticationFailedHandler,
								   CairoHttpMessageAccessDeniedHandler cairoAccessDeniedHandler,
								   CairoHttpMessageAuthenticationSuccessHandler successHandler) throws Exception {
		return http
			.csrf().disable()
			.authorizeRequests(authorizeRequests -> authorizeRequests
				.mvcMatchers("/**").authenticated()
			)
			.exceptionHandling()
//			.authenticationEntryPoint((request, response, authException) -> {
//				throw authException;
//			})
//			.accessDeniedHandler((request, response, accessDeniedException) -> {
//				throw accessDeniedException;
//			})
			.and()

			.csrf().disable()
			.sessionManagement().disable()

			.formLogin()
			.failureHandler(cairoAuthenticationFailedHandler)
			.successHandler(successHandler)
			.and()

			.build();
	}

	@Bean
	WebSecurityCustomizer webSecurityCustomizer() {
		return (web) -> web.ignoring().antMatchers("/", "/actuator/**", "/favicon.ico", "**/favicon.ico", "/public/**");
	}
}
